import myHomeColumnsLess from "./myHomeColumns.module.less";
import NoData from "@/components/noData/noData";
import { Modal, Form, Input, Upload, message } from "antd";
import type { FormProps, UploadFile } from "antd";
import { UploadApi } from "@/http/api/upload";
import { CreateColumnsApi } from "@/http/api/columns";
import { useState } from "react";
import { PlusOutlined } from "@ant-design/icons";

function MyHomeColumns() {
  const { TextArea } = Input;
  const [form] = Form.useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  type FieldType = {
    ColumnName?: string;
    ColumnIntroduction?: string;
    ColumnCover?: string;
  };

  const onFinish: FormProps<FieldType>["onFinish"] = (values) => {
    console.log("Success:", values);
  };

  const onFinishFailed: FormProps<FieldType>["onFinishFailed"] = (
    errorInfo
  ) => {
    console.log("Failed:", errorInfo);
  };
  const onCheck = async () => {
    try {
      const values = await form.validateFields();
      console.log("Success:", values);
      CreateColumns();
    } catch (errorInfo) {
      console.log("Failed:", errorInfo);
    }
  };
  const handlePreview = async (file: any) => {
    const form = new FormData();
    form.append("file", file.file);
    const res: any = await UploadApi(form);
    console.log("上传结果", res);
    if (res.status === 0) {
      const FileList = [
        {
          uid: "1",
          name: res.name,
          url: res.url,
        },
      ];
      setFileList(FileList);
      console.log("上传文件", FileList);
    }
    return false;
  };
  const CreateColumns = async () => {
    const params = {
      ColumnName: form.getFieldsValue().ColumnName,
      ColumnIntroduction: form.getFieldsValue().ColumnIntroduction,
      ColumnCover: fileList.length > 0 ? fileList[0].url : "",
    };
    const res: any = await CreateColumnsApi(params);
    console.log("创建专栏结果", res);
    if (res.status === 0) {
      message.success("专栏创建需要等待审核");
      handleCancel();
      form.resetFields();
      setFileList([]);
    }
  };
  const cancelCreate = () => {
    handleCancel();
    form.resetFields();
    setFileList([]);
  };

  return (
    <>
      <div className={myHomeColumnsLess.myHomeColumnsContent}>
        <div className="nodata">
          <NoData noDataTips="这里什么也没有">
            <div className="btn" onClick={showModal}>
              新建专栏
            </div>
          </NoData>
        </div>
        <Modal
          title={null}
          open={isModalOpen}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={null}
          wrapClassName={"myHomeColumnsModal"}
          getContainer={false}
        >
          <div className="titleAll">新建专栏</div>
          <div className="contentBox">
            <div className="tips">
              欢迎大家使用稀土掘金专栏，让你的写作更加体系化~
            </div>
            <div className="formContent">
              <Form
                form={form}
                name="basic"
                initialValues={{ remember: true }}
                onFinish={onFinish}
                onFinishFailed={onFinishFailed}
                autoComplete="off"
                layout={"vertical"}
              >
                <Form.Item<FieldType>
                  label="专栏名称"
                  name="ColumnName"
                  rules={[
                    {
                      required: true,
                      message: "请输入专栏名称",
                    },
                  ]}
                >
                  <Input
                    placeholder="请输入专栏名称"
                    showCount
                    maxLength={50}
                    variant="filled"
                  />
                </Form.Item>

                <Form.Item<FieldType>
                  label="专栏简介"
                  name="ColumnIntroduction"
                  rules={[
                    {
                      required: true,
                      message: "请输入专栏简介",
                    },
                  ]}
                >
                  <TextArea
                    rows={4}
                    showCount
                    maxLength={150}
                    placeholder="请输入专栏简介"
                    variant="filled"
                  />
                </Form.Item>
                <Form.Item<FieldType> label="专栏封面" name="ColumnCover">
                  <Upload customRequest={handlePreview} showUploadList={false}>
                    {fileList.length > 0 ? (
                      <div className="showImg">
                        <img src={fileList[0].url} alt="" />
                      </div>
                    ) : (
                      <div className="uploadCover">
                        <div className="icon">
                          <PlusOutlined />
                        </div>
                        <div className="titleUpload">点击上传封面</div>
                        <div className="tipsUpload">建议尺寸：480*270px</div>
                      </div>
                    )}
                  </Upload>
                </Form.Item>
              </Form>
            </div>
            <div className="bottom_btn">
              <div className="cancel_btn" onClick={cancelCreate}>
                取消
              </div>
              <div className="confirm_btn" onClick={onCheck}>
                确定
              </div>
            </div>
          </div>
        </Modal>
      </div>
    </>
  );
}

export default MyHomeColumns;
